<?php

namespace app\modules\mall\controllers;

use Yii;
use app\controllers\ApiController;
use app\modules\mall\models\Order;
use app\modules\mall\models\Cart;
use app\modules\mall\models\Goods;
use app\modules\mall\models\Alipay;
use app\modules\mall\models\City;
use app\modules\mall\models\Message;
use app\modules\mall\models\Wxpay;
use app\modules\mall\models\Finance;
use Exception;

class OrderController extends ApiController {
    
    const ORDER_WAITPAY     = 0;
    const ORDER_PAY         = 1;
    const ORDER_DELIVERY    = 2;
    const ORDER_DONE        = 3;
    const ORDER_CLOSE       = 5;
    
    const ALIPAYMENT        = 1;
    const WXPAYMENT         = 2;
    
    const ORDER_ID          = 1;
    const PARENT_ORDER_ID   = 2;
    
    const ACCOUNT_DEAL      = 1; //财务记录类型，交易
    
    /**
     * 直接购买-创建订单
     * @todo 接受$transportMethod参数
     */
    public function actionCreatedirect() {
        $data = [];
        if($this->isLogin()) {
            $uid = $this->_getUid();
        } else {
            $this->_exit(40005);
        }
        //接受订单中商品信息
        $goodsInfo = trim(Yii::$app->request->post('goodsInfo'));
        $goodsInfo = json_decode($goodsInfo, 1);
        //收件人信息
        $receiverName       = trim(Yii::$app->request->post('receiverName'));
        $receiverAddress    = trim(Yii::$app->request->post('receiverAddress'));
        $receiverPhone      = trim(Yii::$app->request->post('receiverPhone'));
        //收件人国家，省市区
        $receiverCountry    = trim(Yii::$app->request->post('receiverCountry'));
        $receiverProvince   = trim(Yii::$app->request->post('receiverProvince', 0));
        $receiverCity       = trim(Yii::$app->request->post('receiverCity', 0));
        $receiverTown       = trim(Yii::$app->request->post('receiverTown', 0));
        $transportMethod    = 1;
        $city = new City();
        $receiverLocation = $city->getNameById($receiverCountry) . $city->getNameById($receiverProvince)
        . $city->getNameById($receiverCity) . $city->getNameById($receiverTown);
        $receiverCode       = trim(Yii::$app->request->post('receiverCode'));
        
        if(!$goodsInfo || !$receiverAddress || !$receiverCode || !$receiverName || !is_numeric($receiverCountry) || !is_numeric($receiverProvince) || !is_numeric($receiverCity) || !is_numeric($receiverTown) || !$receiverPhone) {
            $this->_exit(-1);
        }
        
        //创建订单时，生成订单号
        $parent_order_id = $this->create_order_num();
        
        $model  = new Order();
        $goods  = new Goods();
        $orderids   = [];
        
        $transaction = $model::db()->beginTransaction();
        
        try {
            $arr = [];
            $arr_tpl = [];
            $order_id = $this->create_order_num();
            
            $info = $goodsInfo[0];
        
            $tmp = [];
            $tmp['uid'] = $uid;
            $tmp['parent_order_id'] = $parent_order_id;
            if(!isset($info['skuid'])) {
                $info['skuid'] = 0;
            }
            if(!is_numeric($info['goodsid']) || !is_numeric($info['skuid']) || !is_numeric($info['num']) || $info['num'] < 1) {
                $this->_exit(-1);
            }
    
            $gInfo = $goods->getGoodsInfo($info);
    
            if(empty($gInfo)) {
                $this->_exit(40010);
            } elseif($gInfo['is_delete']>0 || $gInfo['is_up_down']>0) {
                $this->_exit(40020, $gInfo['name'] . "已下架");
            }
            if($info['skuid']) {
                $skuInfo = $goods->getSkuinfo($info['skuid'], $info['goodsid']);
    
                if(empty($skuInfo)) {
                    $this->_exit(40010);
                }
                $inventory = $skuInfo['inventory'];
            } else {
                $inventory = $gInfo['inventory'];
            }
    
            if($info['num'] > $inventory) {
                $this->_exit(40016, $gInfo['name'] . "库存不足");
            }
            $gInfo['shopname'] = $goods->getShopName($gInfo['sid']);
            
            $tmp['goods_id']    = $info['goodsid'];
            $tmp['order_id']    = $order_id;
            $tmp['shop_id']     = $gInfo['sid'];
            $tmp['shop_name']   = $gInfo['shopname'];
            $tmp['goods_name']  = $gInfo['name'];
            $tmp['cid']         = $gInfo['cid'];
            $tmp['parameter']   = $gInfo['parameter'];
            $tmp['details']     = $gInfo['details'];
            $tmp['skuid']       = $info['skuid'];
            $tmp['num']         = $info['num'];
    
            if($info['skuid']) {
                $tmp['picid']       = $skuInfo['picids'];
                $tmp['price']       = $skuInfo['price'];
                $tmp['real_price']  = $skuInfo['real_price'];
                $tmp['unit']        = $skuInfo['unit'];
                $tmp['size']        = $skuInfo['size'];
                $tmp['color']       = $skuInfo['color'];
            } else {
                $tmp['picid']       = intval($gInfo['main_pic']);
                $tmp['price']       = $gInfo['price'];
                $tmp['real_price']  = $gInfo['real_price'];
                $tmp['unit']        = $gInfo['unit'];
                $tmp['size']        = '';
                $tmp['color']       = '';
            }
            $tmp['shipping_price']  = $this->getShippingPrice($gInfo['tpl_id'], $info['num'], 1, $receiverCountry, $receiverProvince);
            $tmp['tax_price']       = $this->getGoodsTaxPrice($info['goodsid'], $info['num'], $info['skuid']);
            $tmp['total_price']     = $tmp['price'] * $info['num'] + $tmp['shipping_price'] + $tmp['tax_price'];
            
            $tmp['commission_price'] = round($tmp['total_price'] * Yii::$app->params['commission_rate']);
            
            $tmp['receiver_name']       = $receiverName;
            $tmp['receiver_address']    = $receiverAddress;
            $tmp['receiver_phone']      = $receiverPhone;
            $tmp['receiver_country']    = $receiverCountry;
            $tmp['receiver_province']   = $receiverProvince;
            $tmp['receiver_city']       = $receiverCity;
            $tmp['receiver_town']       = $receiverTown;
            $tmp['receiver_location']   = $receiverLocation;
            $tmp['receiver_code']       = $receiverCode;
            $tmp['words']               = $info['words'];
            $tmp['create_time']         = time();
            $tmp['pay_end_time']        = strtotime("+1 day", time());
            $tmp['modify_time']         = time();
    
            //运费模板相关信息
            $is_free_shipping = $goods->isGoodsLogisticsFree($gInfo['tpl_id']);
            if($is_free_shipping == 1) {
                $tmp['is_free_shipping']    = $is_free_shipping;
                $logisticsInfo = $this->getGoodsLogisticsInfo($gInfo['tpl_id'], $transportMethod, $receiverCountry, $receiverProvince);
                $tmp['cal_method']          = $logisticsInfo['cal_method'];
                $tmp['transport_method']    = $logisticsInfo['transport_method'];
                $tmp['area_ids']            = $logisticsInfo['area_ids'];
                $tmp['area_ids_label']      = $logisticsInfo['area_ids_label'];
                $tmp['amont_unit']          = $logisticsInfo['amont_unit'];
                $tmp['count_unit']          = $logisticsInfo['count_unit'];
                $tmp['first_count']         = $logisticsInfo['first_count'];
                $tmp['first_amount']        = $logisticsInfo['first_amount'];
                $tmp['add_count']           = $logisticsInfo['add_count'];
                $tmp['add_amount']          = $logisticsInfo['add_amount'];
            } else {
                $tmp['is_free_shipping']    = $is_free_shipping;
                $tmp['cal_method']          = 0;
                $tmp['transport_method']    = $transportMethod;
                $tmp['area_ids']            = '';
                $tmp['area_ids_label']      = '';
                $tmp['amont_unit']          = '';
                $tmp['count_unit']          = '';
                $tmp['first_count']         = '';
                $tmp['first_amount']        = 0;
                $tmp['add_count']           = '';
                $tmp['add_amount']          = 0;
            }
    
            //添加到订单中
            $model->addOrder($tmp);
    
            $inventory -= $info['num'];
            if($inventory < 0) {
                $this->_exit(40016, $gInfo['name'] . "库存不足");
            }
            //更新库存信息
            if($info['skuid']) {
                $goods->updateGoodsSkuInventory($info['goodsid'], $info['skuid'], $inventory);
            } else {
                $goods->updateGoodsInventory($info['goodsid'], $inventory);
            }
            
            $returnData = [];
            $returnData['totalPrice'] = $tmp['total_price'];
            $returnData['orderId'] = $tmp['order_id'];
            $returnData['orderType'] = self::ORDER_ID;
            
            $transaction->commit();
            $this->_exit(0, $returnData);
        } catch(Exception $e) {
            var_dump($e->getMessage());
            $transaction->rollback();
            $this->_exit(40017);
        }
    }
    /**
     * 购物车-创建订单
     * @todo 接收transportMethod参数（1-快递，2-物流）
     * POST
     */
    public function actionCreate() {
        $data = [];
        if($this->isLogin()) {
            $uid = $this->_getUid();
        } else {
            $this->_exit(40005);
        }
        //接受订单中商品信息
        $goodsInfo = trim(Yii::$app->request->post('goodsInfo'));
        $goodsInfo = json_decode($goodsInfo, 1);
        //收件人信息
        $receiverName       = trim(Yii::$app->request->post('receiverName'));
        $receiverAddress    = trim(Yii::$app->request->post('receiverAddress'));
        $receiverPhone      = trim(Yii::$app->request->post('receiverPhone'));
        //收件人国家，省市区
        $receiverCountry    = trim(Yii::$app->request->post('receiverCountry'));
        $receiverProvince   = trim(Yii::$app->request->post('receiverProvince', 0));
        $receiverCity       = trim(Yii::$app->request->post('receiverCity', 0));
        $receiverTown       = trim(Yii::$app->request->post('receiverTown', 0));
        $transportMethod    = 1;
        $city = new City();
        $receiverLocation = $city->getNameById($receiverCountry) . $city->getNameById($receiverProvince)
        . $city->getNameById($receiverCity) . $city->getNameById($receiverTown);
        $receiverCode       = trim(Yii::$app->request->post('receiverCode'));
        
        if(!$goodsInfo || !$receiverAddress || !$receiverCode || !$receiverName || !is_numeric($receiverCountry) || !is_numeric($receiverProvince) || !is_numeric($receiverCity) || !is_numeric($receiverTown) || !$receiverPhone) {
            $this->_exit(-1);
        }
        
        //创建订单时，生成订单号
        $parent_order_id = $this->create_order_num();
        
        $model  = new Order();
        $goods  = new Goods();
        $cart   = new Cart();
        $shopids    = [];
        $orderids   = [];
        
        $transaction = $model::db()->beginTransaction();
        
        try {
            $arr = [];
            $arr_tpl = [];
            foreach($goodsInfo as $info) {
                
                $tmp = [];
                $tmp['uid'] = $uid;
                $tmp['parent_order_id'] = $parent_order_id;
                if(!isset($info['skuid'])) {
                    $info['skuid'] = 0;
                }
                if(!is_numeric($info['goodsid']) || !is_numeric($info['skuid']) || !is_numeric($info['num']) || $info['num'] < 1) {
                    $this->_exit(-1);
                }
                
                $gInfo = $goods->getGoodsInfo($info);
                
                if(empty($gInfo)) {
                    $this->_exit(40010);
                } elseif($gInfo['is_delete']>0 || $gInfo['is_up_down']>0) {
                    $this->_exit(40020, $goodsInfo['name'] . "已下架");
                }
                if($info['skuid']) {
                    $skuInfo = $goods->getSkuinfo($info['skuid'], $info['goodsid']);
                    
                    if(empty($skuInfo)) {
                        $this->_exit(40010);
                    }
                    $inventory = $skuInfo['inventory'];
                } else {
                    $inventory = $gInfo['inventory'];
                }
                
                if($info['num'] > $inventory) {
                    $this->_exit(40016, $gInfo['name'] . "库存不足");
                }
                $gInfo['shopname'] = $goods->getShopName($gInfo['sid']);
                
                //根据不同店铺拆单
                if(!in_array($gInfo['sid'], $shopids)) {
                    $shopids[] = $gInfo['sid'];
                    $order_id = $this->create_order_num();
                    $orderids[$gInfo['sid']] = $order_id;
                } else {
                    $order_id = $orderids[$gInfo['sid']];
                }
                
                $tmp['goods_id']    = $info['goodsid'];
                $tmp['order_id']    = $order_id;
                $tmp['shop_id']     = $gInfo['sid'];
                $tmp['shop_name']   = $gInfo['shopname'];
                $tmp['goods_name']  = $gInfo['name'];
                $tmp['cid']         = $gInfo['cid'];
                $tmp['parameter']   = $gInfo['parameter'];
                $tmp['details']     = $gInfo['details'];
                $tmp['skuid']       = $info['skuid'];
                $tmp['num']         = $info['num'];
                
                if($info['skuid']) {
                    $tmp['picid']       = $skuInfo['picids'];
                    $tmp['price']       = $skuInfo['price'];
                    $tmp['real_price']  = $skuInfo['real_price'];
                    $tmp['unit']        = $skuInfo['unit'];
                    $tmp['size']        = $skuInfo['size'];
                    $tmp['color']       = $skuInfo['color'];
                } else {
                    $tmp['picid']       = intval($gInfo['main_pic']);
                    $tmp['price']       = $gInfo['price'];
                    $tmp['real_price']  = $gInfo['real_price'];
                    $tmp['unit']        = $gInfo['unit'];
                    $tmp['size']        = '';
                    $tmp['color']       = '';
                }
                $tmp['shipping_price']  = 0;
                $tmp['tax_price']       = $this->getGoodsTaxPrice($info['goodsid'], $info['num'], $info['skuid']);
                $tmp['total_price']     = 0;
                
                $tmp['receiver_name']       = $receiverName;
                $tmp['receiver_address']    = $receiverAddress;
                $tmp['receiver_phone']      = $receiverPhone;
                $tmp['receiver_country']    = $receiverCountry;
                $tmp['receiver_province']   = $receiverProvince;
                $tmp['receiver_city']       = $receiverCity;
                $tmp['receiver_town']       = $receiverTown;
                $tmp['receiver_location']   = $receiverLocation;
                $tmp['receiver_code']       = $receiverCode;
                $tmp['words']               = $info['words'];
                $tmp['create_time']         = time();
                $tmp['pay_end_time']        = strtotime("+1 day", time());
                $tmp['modify_time']         = time();
                
                //运费模板相关信息
                $is_free_shipping = $goods->isGoodsLogisticsFree($gInfo['tpl_id']);
                if($is_free_shipping == 1) {
                    $tmp['is_free_shipping']    = $is_free_shipping;
                    $logisticsInfo = $this->getGoodsLogisticsInfo($gInfo['tpl_id'], $transportMethod, $receiverCountry, $receiverProvince);
                    $tmp['cal_method']          = $logisticsInfo['cal_method'];
                    $tmp['transport_method']    = $logisticsInfo['transport_method'];
                    $tmp['area_ids']            = $logisticsInfo['area_ids'];
                    $tmp['area_ids_label']      = $logisticsInfo['area_ids_label'];
                    $tmp['amont_unit']          = $logisticsInfo['amont_unit'];
                    $tmp['count_unit']          = $logisticsInfo['count_unit'];
                    $tmp['first_count']         = $logisticsInfo['first_count'];
                    $tmp['first_amount']        = $logisticsInfo['first_amount'];
                    $tmp['add_count']           = $logisticsInfo['add_count'];
                    $tmp['add_amount']          = $logisticsInfo['add_amount'];
                } else {
                    $tmp['is_free_shipping']    = $is_free_shipping;
                    $tmp['cal_method']          = 0;
                    $tmp['transport_method']    = $transportMethod;
                    $tmp['area_ids']            = '';
                    $tmp['area_ids_label']      = '';
                    $tmp['amont_unit']          = '';
                    $tmp['count_unit']          = '';
                    $tmp['first_count']         = '';
                    $tmp['first_amount']        = 0;
                    $tmp['add_count']           = '';
                    $tmp['add_amount']          = 0;
                }
                $arr_tpl[$gInfo['sid']][$gInfo['tpl_id']] += $info['num'];
                $arr[$gInfo['sid']]['taxPrice'] += $tmp['tax_price'];
                $arr[$gInfo['sid']]['totalPrice'] += $tmp['price'] * $info['num'];
                $arr[$gInfo['sid']]['orderid']   = $order_id;
                //从购物车中删除
                
                $cartData = [];
                $cartData['uid'] = $uid;
                $cartData['goodsid'] = $info['goodsid'];
                $cartData['skuid'] = $info['skuid'];
                
                if($cart->hasGoods($uid, $info['goodsid'], $info['skuid'])) {
                    
                    if(!$cart->delCart($cartData)) {
                        $this->_exit(-1);
                    }
                } else {
                    $this->_exit(40014);
                }
                
                //添加到订单中
                $model->addOrder($tmp);
                
                $inventory -= $info['num'];
                if($inventory < 0) {
                    $this->_exit(40016, $gInfo['name'] . "库存不足");
                }
                //更新库存信息
                if($info['skuid']) {
                    $goods->updateGoodsSkuInventory($info['goodsid'], $info['skuid'], $inventory);
                } else {
                    $goods->updateGoodsInventory($info['goodsid'], $inventory);
                }
            }
            
            foreach($arr_tpl as $key=>$value) {
                $shopid = $key;
                $shippingPrice = 0;
                foreach($value as $k=>$v) {
                    $tplid = $k;
                    $num = $v;
                    $shippingPrice += $this->getShippingPrice($tplid, $num, $transportMethod, $receiverCountry, $receiverProvince);
                }
                $arr[$shopid]['shippingPrice'] = $shippingPrice;
                $arr[$shopid]['uid'] = $uid;
            }
            $returnData = [];
            foreach($arr as $key=>$value) {
                $returnData['totalPrice'] += $value['shippingPrice'] + $value['taxPrice'] + $value['totalPrice'];
                $res = $model->updateOrderPrice($value);
            }
            $transaction->commit();
            
            $returnData['orderId'] = $tmp['parent_order_id'];
            $returnData['orderType'] = self::PARENT_ORDER_ID;
            $this->_exit(0, $returnData);
        } catch(Exception $e) {
            var_dump($e->getMessage());
            $transaction->rollback();
            $this->_exit(40017);
        }
    }
    
    /**
     * 查看我所有订单
     * GET
     */
    public function actionList() {
        $data = [];
        if($this->isLogin()) {
            $data['uid'] = $this->_getUid();
        } else {
            $this->_exit(40005);
        }
        $data['state'] = trim(Yii::$app->request->get('state', 0));
        $data['page'] = $this->_getPage();
        $data['state'] = (int)$data['state'];
        
        if($data['state'] < 0 || !is_numeric($data['state'])) {
            $this->_exit(-1);
        }
        
        $data['size'] = 4;
        
        $model = new Order();
        $goodsModel = new Goods();
        
        //分页获取订单id
        $orderIds = $model->getOrderIds($data);
        
        $arr = [];
        $orders = [];
        foreach($orderIds as $key=>$value) {
            $orderId = $value['order_id'];
            $list = $model->getOrderList($orderId);
            foreach($list as $tmp) {
                $orders[$key]['shopid']     = $tmp['shop_id'];
                $orders[$key]['shopname']   = $tmp['shop_name'];
                $orders[$key]['tel']        = $goodsModel->getShopInfo($tmp['shop_id'])['tel_phone'];
                $orders[$key]['state']      = $tmp['state'];
                $orders[$key]['totalNum']   += $tmp['num'];
                $orders[$key]['totalShipping'] = $tmp['shipping_price'];
                $orders[$key]['totalTax'] += $tmp['tax_price'];
                $orders[$key]['totalPrice'] = $tmp['total_price'];
                $orders[$key]['isComment'] = $tmp['is_comment'];
                $orders[$key]['orderId'] = $orderId;
                $orders[$key]['list'][] = [
                    'goods_id'      => $tmp['goods_id'],
                    'goods_name'    => htmlspecialchars_decode($tmp['goods_name']),
                    'skuid'         => $tmp['skuid'],
                    'picid'         => $tmp['picid'],
                    'price'         => $tmp['price'],
                    'unit'          => $tmp['unit'],
                    'num'           => $tmp['num'],
                    'size'          => $tmp['size'],
                    'color'         => $tmp['color']
                ];
            }
        }
        $arr['orders'] = $orders;
        $arr['hasMsg'] = $this->redis->get($data['uid'] . Yii::$app->params['rediskeys']['user_news']) > 0 ? '1' : '0';
        $this->_exit(0, $arr);
    }
    /**
     * 得到未评论订单
     */
    public function actionUncommentlist() { 
        if($this->isLogin()) {
            $data['uid'] = $this->_getUid();
        } else {
            $this->_exit(40005);
        }
        $data['page'] = $this->_getPage();
        $data['size'] = 4;
        $data['state'] = 3;
        $model = new Order();
        $goodsModel = new Goods();
        $orderIds = $model->getUncommentOrderIds($data);
        
        $arr = [];
        $orders = [];
        foreach($orderIds as $key=>$value) {
            $orderId = $value['order_id'];
            $list = $model->getOrderList($orderId);
            foreach($list as $tmp) {
                $orders[$key]['orderId']    = $orderId;
                $orders[$key]['shopid']     = $tmp['shop_id'];
                $orders[$key]['shopname']   = $tmp['shop_name'];
                $orders[$key]['tel']        = $goodsModel->getShopInfo($tmp['shop_id'])['tel_phone'];
                $orders[$key]['state']      = $tmp['state'];
                $orders[$key]['totalNum']   += $tmp['num'];
                $orders[$key]['totalShipping'] += $tmp['shipping_price'];
                $orders[$key]['totalTax'] += $tmp['tax_price'];
                $orders[$key]['totalPrice'] += $tmp['total_price'];
                $orders[$key]['list'][] = [
                    'goods_id'      => $tmp['goods_id'],
                    'goods_name'    => htmlspecialchars_decode($tmp['goods_name']),
                    'skuid'         => $tmp['skuid'],
                    'picid'         => $tmp['picid'],
                    'price'         => $tmp['price'],
                    'unit'          => $tmp['unit'],
                    'num'           => $tmp['num'],
                    'size'          => $tmp['size'],
                    'color'         => $tmp['color']
                ];
            }
        }
        $arr['orders'] = $orders;
        $arr['hasMsg'] = $this->redis->get($data['uid'] . Yii::$app->params['rediskeys']['user_news']) > 0 ? '1' : '0';
        $this->_exit(0, $arr);
    }
    /**
     * 订单搜索
     * POST
     */
    public function actionSearch() {
        $data = [];
        if($this->isLogin()) {
            $data['uid'] = $this->_getUid();
        } else {
            $this->_exit(40005);
        }
        $data['orderid'] = trim(Yii::$app->request->post('orderid'));
        $data['page'] = $this->_getPage();
        $data['size'] = 4;
        if(!is_numeric($data['orderid'])) {
            $this->_exit(-1);
        } 
        $model = new Order();
        $orderIds = $model->getSearchOrderIds($data);
        $arr = [];
        $orders = [];
        foreach($orderIds as $value) {
            $orderId = $value['order_id'];
            $orders[] = $model->getOrderList($orderId);
        }
        $arr['orders'] = $orders;
        $arr['hasMsg'] = $this->redis->get($data['uid'] . Yii::$app->params['rediskeys']['user_news']) > 0 ? '1' : '0';
        $this->_exit(0, $arr);
    }
    /**
     * 订单详情
     * GET
     */
    public function actionOrderdetail() {
        $data = [];
        if($this->isLogin()) {
            $data['uid'] = $this->_getUid();
        } else {
            $this->_exit(40005);
        }
        $data['orderid'] = trim(Yii::$app->request->get('orderid'));
        if(!is_numeric($data['orderid'])) {
            $this->_exit(-1);
        }
        $model = new Order();
        $goodsModel = new Goods();
        $orderDetail = $model->getOrderDetail($data);
        if(!empty($orderDetail)) {
            $arr = [];
            foreach($orderDetail as $key=>$value) {
                $arr['receiverName']        = $value['receiver_name'];
                $arr['receiverPhone']       = $value['receiver_phone'];
                $arr['receiverLocation']    = $value['receiver_location'];
                $arr['receiverAddress']     = $value['receiver_address'];
                $arr['words']               = $value['words'];
                $arr['shopname']            = $value['shop_name'];
                $arr['tel']                 = $goodsModel->getShopInfo($value['shop_id'])['tel_phone'];
                $arr['shippingPrice']       = $value['shipping_price'];
                $arr['taxPrice']            += $value['tax_price'];
                $arr['totalPrice']          = $value['total_price'];
                $arr['payType']             = $value['pay_type'];
                $arr['orderId']             = $value['order_id'];
                $arr['createTime']          = $value['create_time'];
                $time = time();
                $arr['payTime']             = $value['pay_time'];
                $arr['deliveryTime']        = $value['delivery_time'];
                $arr['payEndTimestamp']     = ($value['pay_end_time'] > $time) ? ($value['pay_end_time'] - $time) : 0;
                $arr['autoReceiveTimestamp']= ($value['auto_receive_time'] > $time) ? ($value['auto_receive_time'] - $time) : 0;
                $arr['dealTime']            = $value['deal_time'];
                $arr['state']               = $value['state'];
                $arr['isComment']           = $value['is_comment'];
                $arr['goodsList'][] = [
                    'goods_id'      => $value['goods_id'],
                    'goods_name'    => htmlspecialchars_decode($value['goods_name']),
                    'skuid'         => $value['skuid'],
                    'picid'         => $value['picid'],
                    'price'         => $value['price'],
                    'unit'          => $value['unit'],
                    'num'           => $value['num'],
                    'size'          => $value['size'],
                    'color'         => $value['color']
                ];
            }
            $logisticsInfo = $model->getOneLogisticsInfo($data['orderid']);
            $arr['logistics'] = []; 
            if(empty($logisticsInfo)) {
                $arr['logistics'] = null;
            } else { 
                if(in_array($logisticsInfo['logistics_code'], Yii::$app->params['push_logistics_code'])) {
                    $transInfo = $model->getOneLogisticsDetailByNum($logisticsInfo['logistics_num'], $logisticsInfo['logistics_code']);
                    if(!empty($transInfo)) {
                        $arr['logistics']['time']       = $transInfo['time'];
                        $arr['logistics']['context']    = $transInfo['context'];
                    } else {
                        $arr['logistics']['time']       = date('Y-m-d H:i:s');
                        $arr['logistics']['context']    = Yii::$app->params['noLogisticsInfo'];
                    }
                } else {
                    $transInfo = $this->getLogisticsInfo($logisticsInfo['logistics_code'], $logisticsInfo['logistics_num'], 0);
                    $transInfo = json_decode($transInfo, true);
                
                    if($transInfo['status'] == 1) {
                        $arr['logistics']['time']       = $transInfo['data'][0]['time'];
                        $arr['logistics']['context']    = $transInfo['data'][0]['context'];
                    } else {
                        $arr['logistics']['time']    = date('Y-m-d H:i:s');
                        $arr['logistics']['context'] = Yii::$app->params['noLogisticsInfo'];
                    }
                }
            }
            
            $arr['hasMsg'] = $this->redis->get($data['uid'] . Yii::$app->params['rediskeys']['user_news']) > 0 ? '1' : '0';
            $this->_exit(0, $arr);
        } else {
            $this->_exit(40013);
        }
    }
    /**
     * 取消订单
     * POST
     */
    public function actionCancel() {
        $data = [];
        if($this->isLogin()) {
            $data['uid'] = $this->_getUid();
        } else {
            $this->_exit(40005);
        }
        
        $data['order_id'] = trim(Yii::$app->request->post('orderid'));
        $data['state'] = 5;
        if(!is_numeric($data['order_id'])) {
            $this->_exit(-1);
        }
        
        $model = new Order();
        $goodsModel = new Goods();
        $transaction = $model::db()->beginTransaction();
        try {
            $tmp['orderid'] = $data['order_id'];
            $tmp['uid']     = $data['uid'];
            $orderInfo = $model->getOrderDetail($tmp);
            if(empty($orderInfo)) {
                $this->_exit(40013);
            }
            foreach($orderInfo as $info) {
                if($info['skuid']) {
                    //更新sku库存
                    $goodsModel->addGoodsSkuInventory($info['goods_id'], $info['skuid'], $info['num']);
                } else {
                    //更新商品库存
                    $goodsModel->addGoodsInventory($info['goods_id'], $info['num']);
                }
            }
            $res = $model->cancel($data);
            if($res) {
                $transaction->commit();
                $this->_exit(0);
            } else {
                $this->_exit(-1);
            }
        } catch(Exception $e) {
            echo $e->getMessage();
            $transaction->rollback();
        }
    }
    /**
     * 确认收货
     * POST
     */
    public function actionReceive() {
        $data = [];
        if($this->isLogin()) {
            $data['uid'] = $this->_getUid();
        } else {
            $this->_exit(40005);
        }
        $data['order_id'] = trim(Yii::$app->request->post('orderid'));
        $data['state'] = 3;
        if(!is_numeric($data['order_id'])) {
            $this->_exit(-1);
        }
        $model = new Order();
        if(!$model->hasOrderByOrderid($data['uid'], $data['order_id'])) {
            $this->_exit(40013);
        }
        $res = $model->receive($data);
        if($res) {
            $this->_exit(0);
        } else {
            $this->_exit(-1);
        }
    }
    /**
     * 提醒卖家发货
     * POST
     */
    public function actionReminddelivery() {
        $data = [];
        if($this->isLogin()) {
            $data['uid'] = $this->_getUid();
        } else {
            $this->_exit(40005);
        }
        $data['order_id'] = trim(Yii::$app->request->post('orderid'));
        $data['state'] = 1;
        if(!is_numeric($data['order_id'])) {
            $this->_exit(-1);
        }
        $model = new Order();
        if(!$model->hasOrderByOrderid($data['uid'], $data['order_id'])) {
            $this->_exit(40013);
        }
        $res = $model->remindDelivery($data);
        if($res) {
            $this->_exit(0, '提醒成功');
        } else {
            $this->_exit(40021);
        }
    }
    /**
     * 删除订单
     */
    public function actionDelete() {
        $data = [];
        if($this->isLogin()) {
            $data['uid'] = $this->_getUid();
        } else {
            $this->_exit(40005);
        }
        
        $data['order_id']   = trim(Yii::$app->request->post('orderid'));
        $data['state']      = trim(Yii::$app->request->post('state'));
        if(!is_numeric($data['order_id']) || !($data['state'] == 3 || $data['state'] == 5)) {
            $this->_exit(-1);
        }
        
        $model = new Order();
        $tmp['orderid'] = $data['order_id'];
        $tmp['uid']     = $data['uid'];
        if(empty($model->getOrderDetail($tmp))) {
            $this->_exit(40013);
        }
        $res = $model->deleteOrder($data);
        if($res) {
            $this->_exit(0);
        } else {
            $this->_exit(-1);
        }
    }
    /**
     * 选择支付方式页面
     * GET
     */
    public function actionPaytype() {
        $this->_exit(0, Yii::$app->params['pay_type']);
    }
    /**
     * 添加购物车内容
     * POST
     */
    public function actionAddcart() {
        $data = [];
        if($this->isLogin()) {
            $uid = $this->_getUid();
        } else {
            $this->_exit(40005);
        }
        
        //接受购物车中的商品信息
        $goodsInfo = trim(Yii::$app->request->post('goodsInfo'));
        $goodsInfo = json_decode($goodsInfo, 1);
        
        if(!$goodsInfo) {
            $this->_exit(-1);
        }
        $model = new Cart();
        $goods = new Goods();
        
        $transaction = $model::db()->beginTransaction();
        try {
            foreach($goodsInfo as $info) {
                $goods_id = $info['goodsid'];
                $skuid = $info['skuid'];
                if(!isset($skuid)) {
                    $skuid = 0;
                }
                $gInfo = $goods->getGoodsInfo(['goodsid'=>$goods_id]);
                if(!is_numeric($goods_id) || !is_numeric($skuid) || !is_numeric($info['num']) || $info['num']<1 || empty($gInfo)) {
                    $this->_exit(-1);
                }
                if($skuid) {
                    $skuInfo = $goods->getSkuinfo($skuid, $goods_id);
                    if($skuInfo) {
                        $inventory = $skuInfo['inventory'];
                    } else {
                        $this->_exit(-1);
                    }
                } else {
                    $inventory = $gInfo['inventory'];
                }
                if($info['num'] > $inventory) {
                    $this->_exit(40016, $gInfo['name'] . "库存不足");
                }
                $info['shopname'] = $goods->getShopName($gInfo['sid']);
                $hasGoods = $model->hasGoods($uid, $goods_id, $skuid);
                
                $info['uid'] = $uid;
                $info['shopid'] = $gInfo['sid'];
                $info['skuid'] = $skuid;
                if($hasGoods) {
                    $model->updateCart($info);
                } else {
                    $model->addCart($info);
                }
            }
            $transaction->commit();
            $this->_exit(0);
        } catch(Exception $e) {
            $transaction->rollback();
            $this->_exit(40018);
        }
    } 
    /**
     * 修改购物车商品数量
     */
    public function actionUpdatecart() {
        $data = [];
        if($this->isLogin()) {
            $uid = $this->_getUid();
        } else {
            $this->_exit(40005);
        }
        
        //接受购物车中的商品信息
        $goodsInfo = trim(Yii::$app->request->post('goodsInfo'));
        $goodsInfo = json_decode($goodsInfo, 1);
        
        if(!$goodsInfo) {
            $this->_exit(-1);
        }
        $model = new Cart();
        $goods = new Goods();
        
        $transaction = $model::db()->beginTransaction();
        try {
            foreach($goodsInfo as $info) {
                $goods_id = $info['goodsid'];
                $skuid = $info['skuid'];
                if(!isset($skuid)) {
                    $skuid = 0;
                }
                $gInfo = $goods->getGoodsInfo(['goodsid'=>$goods_id]);
                if(!is_numeric($goods_id) || !is_numeric($skuid) || !is_numeric($info['num']) || $info['num']<1 || empty($gInfo)) {
                    $this->_exit(-1);
                }
                if($skuid) {
                    $skuInfo = $goods->getSkuinfo($skuid, $goods_id);
                    if($skuInfo) {
                        $inventory = $skuInfo['inventory'];
                    } else {
                        $this->_exit(-1);
                    }
                } else {
                    $inventory = $gInfo['inventory'];
                }
                if($info['num'] > $inventory) {
                    $this->_exit(40016, $gInfo['name'] . "库存不足");
                }
                $info['shopname'] = $goods->getShopName($gInfo['sid']);
                $hasGoods = $model->hasGoods($uid, $goods_id, $skuid);
        
                $info['uid'] = $uid;
                $info['shopid'] = $gInfo['sid'];
                $info['skuid'] = $skuid;
                if($hasGoods) {
                    $model->updateCartByNum($info);
                } 
            }
            $transaction->commit();
            $this->_exit(0);
        } catch(Exception $e) {
            $transaction->rollback();
            $this->_exit(40018);
        }
    }
    /**
     * 删除购物车中的商品
     * POST
     */
    public function actionDelcartgoods() {
        //批量删除
        if($this->isLogin()) {
            $uid = $this->_getUid();
        } else {
            $this->_exit(40005);
        }
        
        $goodsInfo = trim(Yii::$app->request->post('goodsInfo'));
        $goodsInfo = json_decode($goodsInfo, 1);
        
        if(!$goodsInfo) {
            $this->_exit(-1);
        }
        $model = new Cart();
        $transaction = $model::db()->beginTransaction();
        try {
            foreach($goodsInfo as $info) {
                $data = [];
                $data['uid']        = $uid;
                $data['goodsid']    = $info['goodsid'];
                $data['skuid']      = $info['skuid'] ? $info['skuid'] : 0;
                if(!is_numeric($data['goodsid']) || !is_numeric($data['skuid'])) {
                    $this->_exit(-1);
                }
                $has = $model->hasGoods($uid, $data['goodsid'], $data['skuid']);
                if($has) {
                    $res = $model->delCart($data);
                    if(!$res) {
                        $this->_exit(-1);
                    }
                } else {
                    $this->_exit(40014);
                }
            }
            $transaction->commit();
            $this->_exit(0);
        } catch(Exception $e) {
            $transaction->rollback();
            $this->_exit(40019);
        }
    }
    /**
     * 查看购物车中的物品
     * 未分页
     */
    public function actionCartlist() {
        $data = [];
        if($this->isLogin()) {
            $data['uid'] = $this->_getUid();
        } else {
            $this->_exit(40005);
        }
        
        $model = new Cart();
        $cartlist = $model->getCartinfo($data);
        $this->_exit(0, $cartlist);
    }
    /**
     * 查看购物车中物品
     * 通过连接数据库查询
     * GET
     */
    public function actionCartlistpage() {
        $data = [];
        if($this->isLogin()) {
            $data['uid']    = $this->_getUid();
        } else {
            $this->_exit(40005);
        }
//         $data['page']   = $this->_getPage();
//         $data['size']   = 4;
        
        //分页查出店铺数
        $model = new Cart();
        $shopInfo = $model->getCartShopinfo($data);
        $goods = new Goods();
        $arr = [];
        foreach($shopInfo as $key=>$info) {
            //通过shopid和uid查找 
            $cartInfo = $model->getCartinfoByshopid($info);
            
            $isTaxFree = 0;
            $isShippingFree = 0;
            foreach($cartInfo as $k=>$v) {
                $goodsInfo = $goods->getGoodsInfo(['goodsid'=>$v['goods_id']]);
                $cartInfo[$k]['name']       = htmlspecialchars_decode($goodsInfo['name']);
                $cartInfo[$k]['is_delete']  = $goodsInfo['is_delete'];
                $cartInfo[$k]['is_up_down'] = $goodsInfo['is_up_down'];
                $skuid = $v['skuid'];
                
                if($isShippingFree == 1) {
                    $isShippingFree = 1;
                } else {
                    $isShippingFree = $goods->isGoodsLogisticsFree($goodsInfo['tpl_id']);
                }
                
                if(isset($goodsInfo['tax']) && $goodsInfo['tax']>0) {
                    $isTaxFree = 1;
                } else {
                    $isTaxFree = 2;
                }
                
                if($skuid) {
                    $skuinfo = $goods->getSkuinfo($skuid, $v['goods_id']);
                    $cartInfo[$k]['picid'] = intval($skuinfo['picids']);
                    $cartInfo[$k]['size'] = $skuinfo['size'];
                    $cartInfo[$k]['color'] = $skuinfo['color'];
                    $cartInfo[$k]['price'] = $skuinfo['price'];
                    $cartInfo[$k]['real_price'] = $skuinfo['real_price'];
                    $cartInfo[$k]['unit'] = $skuinfo['unit'];
                    $cartInfo[$k]['discount'] = $skuinfo['discount'];
                    $cartInfo[$k]['inventory'] = $skuinfo['inventory'];
                } else {
                    $cartInfo[$k]['picid'] = intval($goodsInfo['main_pic']);
                    $cartInfo[$k]['size'] = '';
                    $cartInfo[$k]['color'] = '';
                    $cartInfo[$k]['price'] = $goodsInfo['price'];
                    $cartInfo[$k]['real_price'] = $goodsInfo['real_price'];
                    $cartInfo[$k]['unit'] = $goodsInfo['unit'];
                    $cartInfo[$k]['discount'] = $goodsInfo['discount'];
                    $cartInfo[$k]['inventory'] = $goodsInfo['inventory'];
                }   
            }
            
            $arr[$key]['shopid'] = $info['shop_id'];
            $arr[$key]['shopname'] = $info['shop_name'];
            $arr[$key]['isTaxFree'] = $isTaxFree;
            $arr[$key]['isShippingFree'] = $isShippingFree;
            $arr[$key]['list'] = $cartInfo;
        }
        $this->_exit(0, $arr);
    }
    /**
     * 添加收件人信息
     * POST
     */
    public function actionAddreceiverinfo() {
        $data = [];
        //收件人信息
        if($this->isLogin()) {
            $data['uid']    = $this->_getUid();
        } else {
            $this->_exit(40005);
        }
        $data['receiver_name']      = trim(Yii::$app->request->post('receiverName'));
        $data['receiver_address']   = trim(Yii::$app->request->post('receiverAddress'));
        $data['receiver_phone']     = trim(Yii::$app->request->post('receiverPhone'));
        $data['receiver_country']   = trim(Yii::$app->request->post('receiverCountry'));
        $data['receiver_province']  = trim(Yii::$app->request->post('receiverProvince'));
        $data['receiver_city']      = trim(Yii::$app->request->post('receiverCity'));
        $data['receiver_town']      = trim(Yii::$app->request->post('receiverTown'));
        $data['receiver_code']      = trim(Yii::$app->request->post('receiverCode'));
        
        $city = new City();
        $data['receiver_location'] = $city->getNameById($data['receiver_country']) . $city->getNameById($data['receiver_province'])
        . $city->getNameById($data['receiver_city']) . $city->getNameById($data['receiver_town']);
        
        if(!$data['receiver_address'] || !$data['receiver_code'] || !$data['receiver_name'] || !is_numeric($data['receiver_country']) || !is_numeric($data['receiver_province']) || !is_numeric($data['receiver_city']) || !is_numeric($data['receiver_town']) || !is_numeric($data['receiver_phone'])) {
            $this->_exit(-1);
        }
        $model = new Order();
        $ret = $model->getReceiverInfo($data['uid']);
        if(empty($ret)) {
            $res = $model->addReceiverInfo($data);
            if($res) {
                $this->_exit(0, ['receiveid'=>$res]);
            } else {
                $this->_exit(-1);
            }
        } else {
            $this->_exit(40022);
        }
    }
    
    /**
     * 修改收件人信息
     */
    public function actionUpdatereceiverinfo() {
        $data = [];
        //收件人信息
        if($this->isLogin()) {
            $data['uid'] = $this->_getUid();
        } else {
            $this->_exit(40005);
        }
        $data['id']                 = trim(Yii::$app->request->post('id'));
        $data['receiver_name']      = trim(Yii::$app->request->post('receiverName'));
        $data['receiver_address']   = trim(Yii::$app->request->post('receiverAddress'));
        $data['receiver_phone']     = trim(Yii::$app->request->post('receiverPhone'));
        $data['receiver_country']   = trim(Yii::$app->request->post('receiverCountry'));
        $data['receiver_province']  = trim(Yii::$app->request->post('receiverProvince'));
        $data['receiver_city']      = trim(Yii::$app->request->post('receiverCity'));
        $data['receiver_town']      = trim(Yii::$app->request->post('receiverTown'));
        $data['receiver_code']      = trim(Yii::$app->request->post('receiverCode'));
        
        $city = new City();
        $data['receiver_location'] = $city->getNameById($data['receiver_country']) . $city->getNameById($data['receiver_province'])
        . $city->getNameById($data['receiver_city']) . $city->getNameById($data['receiver_town']);
        
        if(!is_numeric($data['id']) || !$data['receiver_address'] || !$data['receiver_code'] || !$data['receiver_name'] || !is_numeric($data['receiver_country']) || !is_numeric($data['receiver_province']) || !is_numeric($data['receiver_city']) || !is_numeric($data['receiver_town']) || !is_numeric($data['receiver_phone'])) {
            $this->_exit(-1);
        }
        $model = new Order();
        $res = $model->updateReceiverInfo($data);
        if($res) {
            $this->_exit(0);
        } else {
            $this->_exit(-1);
        }
    }
    /**
     * 得到城市列表
     * GET
     */
    public function actionCitylist() {
        $model = new City();
        $arr = [];
        $countries = $model->getAreaByPid(0);
        foreach($countries as $key=>$country) {
            $arr[$key]['id']      = $country['id'];
            $arr[$key]['country'] = $country['name_cn'];
            
            $provinces = $model->getAreaByPid($country['id']);
            if($provinces) {
                foreach($provinces as $k=>$province) {
                    $arr[$key]['level2'][$k]['id'] = $province['id'];
                    $arr[$key]['level2'][$k]['province'] = $province['name_cn'];
                    
                    $cities = $model->getAreaByPid($province['id']);
                    foreach($cities as $subK=>$city) {
                        $arr[$key]['level2'][$k]['level3'][$subK]['id']     = $city['id'];
                        $arr[$key]['level2'][$k]['level3'][$subK]['city']   = $city['name_cn'];
                        $towns = $model->getAreaByPid($city['id']);
                        foreach($towns as $sk=>$town) {
                            $arr[$key]['level2'][$k]['level3'][$subK]['level4'][$sk]['id']   = $town['id'];
                            $arr[$key]['level2'][$k]['level3'][$subK]['level4'][$sk]['town'] = $town['name_cn'];
                        }
                    }
                }
            }
        }
        $this->_exit(0, $arr);
    }
    /**
     * 确认订单
     */
    public function actionConfirmorder() { 
        
        if($this->isLogin()) {
            $uid = $this->_getUid();
        } else {
            $this->_exit(40005);
        }
        
        //收件人信息
        $model = new Order();
        $city = new City();
        $receiverInfo = $model->getReceiverInfo($uid);
        $receiverInfo['receiver_country_name']  = $city->getNameById($receiverInfo['receiver_country']);
        $receiverInfo['receiver_province_name'] = $city->getNameById($receiverInfo['receiver_province']);
        $receiverInfo['receiver_city_name']     = $city->getNameById($receiverInfo['receiver_city']);
        $receiverInfo['receiver_town_name']     = $city->getNameById($receiverInfo['receiver_town']);
        if($receiverInfo) {
            $country    = $receiverInfo['receiver_country'];
            $province   = $receiverInfo['receiver_province'];
        } else {
            $receiverInfo = null;
            $country = 0;
            $province = 0;
        }
        $goodsInfo  = trim(Yii::$app->request->post('goodsInfo'));
        
        $transportMethod = $this->_validateNum(trim(Yii::$app->request->post('transportMethod', 1)));
        
        $goodsInfo = json_decode($goodsInfo, 1);
        if(!$goodsInfo) {
            $this->_exit(-1);
        }
        
        $model = new Goods();
        $arr = [];
        $tmp = [];
        foreach($goodsInfo as $key=>$value) {
            $tmp_goods = [];
            $gInfo = $model->getGoodsInfo(['goodsid'=>$value['goodsid']]);
            $tmp[$gInfo['sid']][$gInfo['tpl_id']] += $value['num'];
            $arr[$gInfo['sid']]['tax'] += $this->getGoodsTaxPrice($value['goodsid'], $value['num'], $value['skuid']);
            
            $tmp_goods['id'] = $gInfo['id'];
            $tmp_goods['name'] = htmlspecialchars_decode($gInfo['name']);
            $tmp_goods['main_pic'] = $gInfo['main_pic'];
            $tmp_goods['num'] = $value['num'];
            
            if($value['skuid'] > 0) {
                $skuInfo = $model->getSkuinfo($value['skuid'], $value['goodsid']);
                if(empty($skuInfo)) {
                    $this->_exit(-1);
                } else {
                    $arr[$gInfo['sid']]['totalPrice'] += $value['num']*$skuInfo['price'];
                    $tmp_goods['skuid'] = $skuInfo['id'];
                    $tmp_goods['price'] = $skuInfo['price'];
                    $tmp_goods['color'] = $skuInfo['color'];
                    $tmp_goods['size'] = $skuInfo['size'];
                }
            } else {
                $arr[$gInfo['sid']]['totalPrice'] += $gInfo['price']*$value['num'];
                $tmp_goods['skuid'] = '0';
                $tmp_goods['price'] = $gInfo['price'];
                $tmp_goods['color'] = '';
                $tmp_goods['size'] = '';
            }
            if(!isset($arr[$gInfo['sid']]['logisticsEffect'])) {
                $arr[$gInfo['sid']]['logisticsEffect'] = '00:00';
            }
            if(!isset($arr[$gInfo['sid']]['serviceDays'])) {
                $arr[$gInfo['sid']]['serviceDays'] = 0;
            }
            if($this->getNumFromTime($gInfo['logistics_effect']) > $this->getNumFromTime($arr[$gInfo['sid']]['logisticsEffect'])) {
                $arr[$gInfo['sid']]['logisticsEffect'] = $gInfo['logistics_effect'];
            }
            if($gInfo['service_days'] > $arr[$gInfo['sid']]['serviceDays']) {
                $arr[$gInfo['sid']]['serviceDays'] = $gInfo['service_days'];
            }
            $arr[$gInfo['sid']]['goodsList'][] = $tmp_goods;
            $arr[$gInfo['sid']]['totalNum'] += $value['num'];
        }
        $totalInfo = [];
        foreach($tmp as $key=>$value) {
            $shopid = $key;
            $shippingPrice = 0;
            foreach($value as $k=>$v) {
                $tplid = $k;
                $num = $v;
                $shippingPrice += $this->getShippingPrice($tplid, $num, $transportMethod, $country, $province);
            }
            $arr[$shopid]['shipping']   = $shippingPrice;
            $arr[$shopid]['totalPrice'] += $arr[$shopid]['shipping'] + $arr[$shopid]['tax'];
            $arr[$shopid]['shopid']     = $shopid;
            $arr[$shopid]['shopname']   = $model->getShopName($shopid);
            $totalInfo['num']   += $arr[$shopid]['totalNum'];
            $totalInfo['price'] += $arr[$shopid]['totalPrice'];
        }
        
        $this->_exit(0, ['receiverInfo'=>$receiverInfo, 'priceInfo'=>array_values($arr), 'totalInfo'=>$totalInfo]);
    }
    /**
     * 得到用户订单物流信息
     */
    public function actionLogisticsinfo() {
        if($this->isLogin()) {
            $uid = $this->_getUid();
        } else {
            $this->_exit(40005);
        }
        $orderid = trim(Yii::$app->request->get('orderid'));
        $model = new Order();
        $logisticsInfo = $model->getLogisticsInfo($orderid);
        $arr = [];
        
        $arr['hasMsg'] = $this->redis->get($uid . Yii::$app->params['rediskeys']['user_news']) > 0 ? '1' : '0';
        foreach($logisticsInfo as $key=>$info) {
            $index = 0;
            $flag = 0;
            if(!empty($arr['packageInfo'])) {
                foreach($arr['packageInfo'] as $k=>$v) {
                    if($v['packageId'] == $info['package_id']) {
                        $flag = 1;
                        $index = $k;
                        break;
                    }
                }
            }
            
            if($flag === 0) {
                $index = $key;
            }
            $orderInfo = $model->getOrderInfoByPk($info['order_prk_id']);
            $arr['packageInfo'][$index]['packageId']       = $info['package_id'];
            $arr['packageInfo'][$index]['passType']        = $info['pass_type'];
            $arr['packageInfo'][$index]['logisticsName']   = $info['logistics_name'];
            $arr['packageInfo'][$index]['logisticsCode']   = $info['logistics_code'];
            $arr['packageInfo'][$index]['logisticsNum']    = $info['logistics_num'];
            if($info['pass_type'] == 2) {
                $arr['packageInfo'][$index]['logisticsTel']        = $info['logistics_tel'];
                $arr['packageInfo'][$index]['logisticsPersonName'] = $info['logistics_person_name'];
                $arr['packageInfo'][$index]['logisticsPersonTel']  = $info['logistics_person_tel'];
                $arr['packageInfo'][$index]['deliveryTime']        = $info['delivery_time']; 
            }
            
            $arr['packageInfo'][$index]['goodsInfo'][] = $orderInfo;
            
            if($flag === 0) {
                if(in_array($info['logistics_code'], Yii::$app->params['push_logistics_code'])) {
                    $transInfo = $model->getLogisticsDetailByNum($arr['packageInfo'][$index]['logisticsNum'], $info['logistics_code']);
                    if(!empty($transInfo)) {
                        $arr['packageInfo'][$index]['state'] = $transInfo[0]['state'];
                        foreach($transInfo as $k=>$info) {
                            $arr['packageInfo'][$index]['transInfo'][$k]['time']       = $info['time'];
                            $arr['packageInfo'][$index]['transInfo'][$k]['context']    = $info['context'];
                        }
                    } else {
                        $arr['packageInfo'][$index]['state'] = -1; //快递单状态-1：自定义异常
                        $arr['packageInfo'][$index]['transInfo'][0]['time']    = date('Y-m-d H:i:s');
                        $arr['packageInfo'][$index]['transInfo'][0]['context'] = Yii::$app->params['noLogisticsInfo'];
                    }
                } else {
                    $transInfo = $this->getLogisticsInfo($arr['packageInfo'][$index]['logisticsCode'], $arr['packageInfo'][$index]['logisticsNum']);
                    $transInfo = json_decode($transInfo, true);
                    
                    if($transInfo['status'] == 1) {
                        $arr['packageInfo'][$index]['state'] = $transInfo['state']; //快递单状态 0：在途 1：揽件 2：疑难 3：签收 4：退签 5：派件 6：退回
                        foreach($transInfo['data'] as $k=>$v) {
                            $arr['packageInfo'][$index]['transInfo'][$k]['time']       = $v['time'];
                            $arr['packageInfo'][$index]['transInfo'][$k]['context']    =  $v['context'];
                        }
                    } else {
                        $arr['packageInfo'][$index]['state'] = -1; //快递单状态-1：自定义异常
                        $arr['packageInfo'][$index]['transInfo'][0]['time']    = date('Y-m-d H:i:s');
                        $arr['packageInfo'][$index]['transInfo'][0]['context'] = Yii::$app->params['noLogisticsInfo'];
                    }
                }
            }
        }
        $this->_exit(0, $arr);
    }
    /**
     * 根据订单状态订单数
     */
    public function actionNum() {
        
        $model = new Order();
        $uid = $this->_validateNum(trim(Yii::$app->request->get('uid')));
        $state = $this->_validateNum(trim(Yii::$app->request->get('state')));
        $num = $model->getOrderNumByState($uid, $state);
        $this->_exit(0, $num);
    }
    /**
     * 得到未评论订单数
     */
    public function actionUncommentnum() {
        $uid = $this->_validateNum(trim(Yii::$app->request->get('uid')));
        $model = new Order();
        $num = $model->getUncommentNum($uid);
        $this->_exit(0, $num);
    }
    /**
     * 发送订单私信
     * post
     */
    public function actionSendordermsg() {
        $toUid = trim(Yii::$app->request->post('toUid'));
        $orderid = trim(Yii::$app->request->post('orderid'));
        if(!intval($toUid) || !is_numeric($orderid)) {
            $this->_exit(-1);
        }
        $content = trim(Yii::$app->request->post('content'));
        $model = new Message();
        $data['content'] = $content;
        $data['to_uid'] = $toUid;
        $data['orderid'] = $orderid;
        $res = $model->add($data);
        if($res) {
            $this->_exit(0);
        } else {
            $this->_exit(-1);
        }
    }
    /**
     * 阅读订单消息
     */
    public function actionReadordermsg() {
        if($this->isLogin()) {
            $data['uid'] = $this->_getUid();
        } else {
            $this->_exit(40005);
        }
        $data['id'] = trim(Yii::$app->request->post('id'));
        if(!intval($data['id'])) {
            $this->_exit(-1);
        }
        $model = new Message();
        $model->read($data);
        $this->_exit(0);
    }
    /**
     * 是否有新的订单消息
     * 0:无新消息 其他：有新消息
     * GET
     */
    public function actionHasnewordermsg() {
        $uid = $this->_validateNum(trim(Yii::$app->request->get('uid')));
        $model = new Message();
        $num = $model->hasNewMsg($uid);
        $this->_exit(0, $num);
    }
    /**
     * 订单消息列表
     * GET
     */
    public function actionOrdermsglist() {
        $uid = $this->_validateNum(trim(Yii::$app->request->get('uid')));
        $model = new Message();
        $list = $model->msgList($uid);
        $this->_exit(0, $list);
    }
    /**
     * 税费，运费相关
     */
    public function actionFeedetail() {
        //goodsid, num, skuid, shopid, transportMethod, country, province
        $goodsInfo  = trim(Yii::$app->request->post('goodsInfo'));
        $country    = trim(Yii::$app->request->post('country', 0));
        $province   = trim(Yii::$app->request->post('province', 0));
        $transportMethod = trim(Yii::$app->request->post('transportMethod'));
        $goodsInfo = json_decode($goodsInfo, 1);
        if(!$goodsInfo) {
            $this->_exit(-1);
        }
        $model = new Goods();
        $tmp = [];
        $arr = [];
        foreach($goodsInfo as $key=>$value) {
            $gInfo = $model->getGoodsInfo(['goodsid'=>$value['goodsid']]);
            $tmp[$gInfo['sid']][$gInfo['tpl_id']] += $value['num'];
            $arr[$gInfo['sid']]['taxPrice'] += $this->getGoodsTaxPrice($value['goodsid'], $value['num']);
        }
        foreach($tmp as $key=>$value) {
            $shopid = $key;
            $shippingPrice = 0;
            foreach($value as $k=>$v) {
                $tplid = $k;
                $num = $v;
                $shippingPrice += $this->getShippingPrice($tplid, $num, $transportMethod, $country, $province);
            }
            $arr[$shopid]['shippingPrice'] = $shippingPrice;
        }
        $this->_exit(0, $arr);
    }
    /**
     * 获取收货人信息
     */
    public function actionReceiverinfo() {
        //收件人信息
        if($this->isLogin()) {
            $uid = $this->_getUid();
        } else {
            $this->_exit(40005);
        }
        $model = new Order();
        $receiverInfo = $model->getReceiverInfo($uid);
        $this->_exit(0, $receiverInfo);
    }
    /**
     * 得到商品运费模板信息
     * @param unknown $tplid
     * @param unknown $transportMethod
     * @param number $country
     * @param number $province
     */
    private function getGoodsLogisticsInfo($tplid, $transportMethod, $country=0, $province=0) {
        
        $model = new Goods();
        $logisticsInfo = $model->getGoodsLogisticsInfo($tplid, $transportMethod);
        if(empty($logisticsInfo)) {
            $this->_exit(-1);
        }
        foreach($logisticsInfo as $logistics) {
            
            if($logistics['cal_method'] == 1) {
                //按件数
                $areaIds = [];
            
                if($logistics['area_ids']) {
                    $areaIds = explode(',', $logistics['area_ids']);
                    if(in_array($province, $areaIds) || in_array($country, $areaIds)) {
                        return $logistics;
                    }
                }
            } elseif($logisticsInfo['cal_method'] == 2) {
                //todo按重量
                return [];
            } elseif($logisticsInfo['cal_method'] == 3) {
                //todo按体积
                return [];
            }
        }
        
        //得到默认模板信息
        $defaultLogisticsInfo = $model->getGoodsDefaultLogisticsInfo($tplid, $transportMethod);
        if(empty($defaultLogisticsInfo)) {
            $this->_exit(-1);
        }
        return $defaultLogisticsInfo;
    }
    /**
     * 计算商品运费
     * @param unknown $tplId
     * @param unknown $num
     * @param number $country
     * @param number $province
     */
    private function getShippingPrice($tplId, $num, $transportMethod, $country=0, $province=0) {
        $model = new Goods();
        $isFree = $model->isGoodsLogisticsFree($tplId);
        if($isFree == 1) {
            $logisticsInfo = $model->getGoodsLogisticsInfo($tplId, $transportMethod);
            if(empty($logisticsInfo)) {
                $this->_exit(-1);
            }
            foreach($logisticsInfo as $logistics) {
                $shippingMoney = 0;
            
                if($logistics['cal_method'] == 1) {
                    //按件数
                    $areaIds = [];
            
                    if($logistics['area_ids']) {
            
                        $areaIds = explode(',', $logistics['area_ids']);
            
                        if(in_array($province, $areaIds) || in_array($country, $areaIds)) {
                            if($num <= $logistics['first_count']) {
                                $shippingMoney = $logistics['first_amount'];
                            } else {
                                $shippingMoney = $logistics['first_amount'] + ceil(($num - $logistics['first_count'])/$logistics['add_count']) * $logistics['add_amount'];
                            }
                            return $shippingMoney;
                        }
                    }
                } elseif($logisticsInfo['cal_method'] == 2) {
                    //@todo按重量
                    return 0;
                } elseif($logisticsInfo['cal_method'] == 3) {
                    //@todo按体积
                    return 0;
                }
            }
            //获取默认运费
            if($shippingMoney == 0) {
                //得到默认模板信息
                $defaultLogisticsInfo = $model->getGoodsDefaultLogisticsInfo($tplId, $transportMethod);
                if(empty($defaultLogisticsInfo)) {
                    $this->_exit(-1);
                }
                if($num <= $defaultLogisticsInfo['first_count']) {
                    $shippingMoney = $defaultLogisticsInfo['first_amount'];
                } else {
                    $shippingMoney = $defaultLogisticsInfo['first_amount'] + ceil(($num - $defaultLogisticsInfo['first_count']) / $defaultLogisticsInfo['add_count']) * $defaultLogisticsInfo['add_amount'];
                }
                return $shippingMoney;
            }
        } elseif($isFree == 2) {
            return 0;
        }
    }
    /**
     * 计算商品税费
     */
    private function getGoodsTaxPrice($goodsid, $num, $skuid=0) {
        if(!is_numeric($goodsid) || !is_numeric($num) || $num<1) {
            $this->_exit(-1);
        }
        $model = new Goods();
        $goodsInfo = $model->getGoodsInfo(["goodsid"=>$goodsid]);
        if(empty($goodsInfo)) {
            $this->_exit(-1);
        } 
        
        if($skuid > 0) {
            $skuInfo = $model->getSkuinfo($skuid, $goodsid);
            if(empty($skuInfo)) {
                
                $this->_exit(-1);
            }
            
            $ratePrice = $skuInfo['price'] * $num * $goodsInfo['tax'] / 10000.0;
        } else {
            $ratePrice = $goodsInfo['price'] * $num * $goodsInfo['tax'] / 10000.0;
        }
        return round($ratePrice);
    }
    /**
     * 接收支付宝支付异步返回参数
     */
    public function actionAlipaynotify() {
        //一个个接受支付宝异步返回的参数
        //费用要x100
        $alipayData = [];
        $alipayData['notify_time']          = Yii::$app->request->post('notify_time');
        $alipayData['notify_type']          = Yii::$app->request->post('notify_type');
        $alipayData['notify_id']            = Yii::$app->request->post('notify_id');
        $alipayData['sign_type']            = Yii::$app->request->post('sign_type');
        $alipayData['sign']                 = Yii::$app->request->post('sign');
        $alipayData['out_trade_no']         = Yii::$app->request->post('out_trade_no');
        $alipayData['subject']              = Yii::$app->request->post('subject');
        $alipayData['payment_type']         = Yii::$app->request->post('payment_type');
        $alipayData['trade_no']             = Yii::$app->request->post('trade_no');
        $alipayData['trade_status']         = Yii::$app->request->post('trade_status');
        $alipayData['seller_id']            = Yii::$app->request->post('seller_id');
        $alipayData['seller_email']         = Yii::$app->request->post('seller_email');
        $alipayData['buyer_id']             = Yii::$app->request->post('buyer_id');
        $alipayData['buyer_email']          = Yii::$app->request->post('buyer_email');
        $alipayData['total_fee']            = Yii::$app->request->post('total_fee');
        $alipayData['quantity']             = Yii::$app->request->post('quantity');
        $alipayData['price']                = Yii::$app->request->post('price');
        $alipayData['body']                 = Yii::$app->request->post('body');
        $alipayData['gmt_create']           = Yii::$app->request->post('gmt_create');
        $alipayData['gmt_payment']          = Yii::$app->request->post('gmt_payment');
        $alipayData['is_total_fee_adjust']  = Yii::$app->request->post('is_total_fee_adjust');
        $alipayData['use_coupon']           = Yii::$app->request->post('use_coupon');
        $alipayData['discount']             = Yii::$app->request->post('discount');
       
        $orderModel = new Order();
        $alipayModel = new Alipay();
        $financeModel = new Finance();
        
        $alipayData['total_fee'] *= 100;
        $alipayData['price'] *= 100;
        
        //存储支付宝返回参数信息
        
        $res = $orderModel->saveAlipayParams($alipayData);
        if(!$res) {
            return 'fail';
        }
        $alipayModel->alipay_config = Yii::$app->params['alipay'];
        $verityResult = $alipayModel->verifyNotify();
        //var_dump($verityResult);die;
        $transaction = $orderModel::db()->beginTransaction();
        try {
            if($verityResult) {
                if ($alipayData['trade_status'] == 'TRADE_SUCCESS') {
                    $data = [];
                    $data['orderid'] = $alipayData['out_trade_no'];
                    $data['state'] = self::ORDER_PAY;
                    $data['payTime'] = strtotime($alipayData['gmt_payment']);
                    $data['payType'] = self::ALIPAYMENT;
                    $data['transactionNumber'] = $alipayData['trade_no'];
                    
                    //判断orderid有没有
                    $orderModel = new Order();
                    $orderList = $orderModel->getOrderList($data['orderid']);
                    if(empty($orderList)) {
                        $orderList = $orderModel->getOrderListByPOid($data['orderid']);
                        $res = $orderModel->payParentOrder($data);
                    } else {
                        $res = $orderModel->payOrder($data);
                    }
                    if(!$res) {
                        echo 'fail';
                        throw new Exception('更新订单状态失败');
                    } else {
                        $arr = [];
                        foreach($orderList as $value) {
                            $arr[$value['shop_id']]['price']    = $value['total_price'];
                            $arr[$value['shop_id']]['name']     = $value['shop_name'];
                        }
                        foreach($arr as $shopId=>$value) {
                            $price = round($value['price'] * (1 - Yii::$app->params['commission_rate']));
                            $orderModel->updateShopAmount($shopId, $price);
                            $tmpPrice = $value['price']/100.0;
                            $this->cget(Yii::$app->params['mall_back_domain'] . 'mobileapi/logshop?shop_id=' . $shopId . '&money=' . $tmpPrice);
                            $financeData = [];
                            $financeData['serial_number']   = $alipayData['trade_no'];
                            $financeData['shop_id']         = $shopId;
                            $financeData['shop_name']       = $value['name'];
                            $financeData['account_type']    = self::ACCOUNT_DEAL;
                            $financeData['do_money']        = $value['price']/100.0;
                            $financeData['commission']      = $value['price'] * Yii::$app->params['commission_rate'] / 100.0;
                            $financeData['balance']         = $orderModel->getShopAmount($shopId);
                            $financeData['into_time']       = time();
                            $financeData['remarks']         = '';
                            $res = $financeModel->insertDetail($financeData);
                            if(!$res) {
                                echo 'fail';
                                throw new Exception('插入财务明细失败');
                            }
                            $financeModel->updateBalance($financeData['commission']);
                        }
                    }
                    echo 'success';
                } elseif($alipayData['trade_status'] == 'WAIT_BUYER_PAY') {
                    echo 'success';
                }
            } else {
                echo 'fail';
            }
            $transaction->commit();
        } catch(Exception $e) {
            echo 'fail';
            $transaction->rollback();
        }
    }
    /**
     * 接收微信支付异步返回参数
     * @return string
     */
    public function actionWxpaynotify() {
        
        $wxpay = new Wxpay();
        $wxpay->wxpay_config = Yii::$app->params['wxpay'];
        $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
        $retParams = $wxpay->fromXml($xml);
        
        $return = [];
        if($retParams['return_code'] == 'SUCCESS') {
            
            //验证签名
            $mySign = $wxpay->makeSign($retParams);
            if($retParams['sign'] == $mySign) {
                
                $orderModel = new Order();
                $financeModel = new Finance();
                $transaction = $orderModel::db()->beginTransaction();
                try {
                    $orderModel->saveWxpayParams($retParams);
                    
                    $data = [];
                    $data['orderid']    = $retParams['out_trade_no'];
                    $data['state']      = self::ORDER_PAY;
                    $data['payTime']    = strtotime($retParams['time_end']);
                    $data['payType']    = self::WXPAYMENT;
                    $data['transactionNumber'] = $retParams['transaction_id'];
                    
                    $out_trade_no = $retParams['out_trade_no']; //商户订单号
                    $attach = $retParams['attach']; //商家数据包，1-子订单 2-父订单
                    
                    if($attach == self::ORDER_ID) {
                        $orderList = $orderModel->getOrderList($out_trade_no);
                        $res = $orderModel->payOrder($data);
                    } elseif($attach == self::PARENT_ORDER_ID) {
                        $orderList = $orderModel->getOrderListByPOid($out_trade_no);
                        $res = $orderModel->payParentOrder($data);
                    }
                    
                    if($res) {
                        $arr = [];
                        foreach($orderList as $value) {
                            $arr[$value['shop_id']]['price']    = $value['total_price'];
                            $arr[$value['shop_id']]['name']     = $value['shop_name'];
                        }
                        foreach($arr as $shopId=>$value) {
                            $price = round($value['price'] * (1 - Yii::$app->params['commission_rate']));
                            $orderModel->updateShopAmount($shopId, $price);
                            $tmpPrice = $value['price']/100.0;
                            $this->cget(Yii::$app->params['mall_back_domain'] . 'mobileapi/logshop?shop_id=' . $shopId . '&money=' . $tmpPrice);
                            $financeData = [];
                            $financeData['serial_number']   = $retParams['transaction_id'];
                            $financeData['shop_id']         = $shopId;
                            $financeData['shop_name']       = $value['name'];
                            $financeData['account_type']    = self::ACCOUNT_DEAL;
                            $financeData['do_money']        = $value['price']/100.0;
                            $financeData['commission']      = $value['price'] * Yii::$app->params['commission_rate'] / 100.0;
                            $financeData['balance']         = $orderModel->getShopAmount($shopId);
                            $financeData['into_time']       = time();
                            $financeData['remarks']         = '';
                            $res = $financeModel->insertDetail($financeData);
                            if(!$res) {
                                echo 'fail';
                                throw new Exception('插入财务明细失败');
                            }
                            $financeModel->updateBalance($financeData['commission']);
                        }
                    }
                    $transaction->commit();
                } catch(Exception $e) {
                    $transaction->rollback();
                }
                $return['return_code'] = 'SUCCESS';
                $return['msg'] = 'OK';
                
            } else {
                $return['return_code'] = 'FAIL';
                $return['msg'] = '签名错误';
            }
        } else {
            $return['return_code'] = $retParams['return_code'];
            $return['msg'] = $retParams['msg'];
        }
        $xml = $wxpay->toXml($return);
        return $xml;
    }
    /**
     * 订单支付
     * GET
     */
    public function actionOrderpay() {
        
        if($this->isLogin()) {
            $uid = $this->_getUid();
        } else {
            $this->_exit(40005);
        }
        $orderid = $this->_validateNum(Yii::$app->request->get('orderid'));
        $payType = $this->_validateNum(Yii::$app->request->get('payType'));
        $orderType = $this->_validateNum(Yii::$app->request->get('orderType', 1));
        
        $orderModel = new Order();
        if($orderType == self::ORDER_ID) {
            $orderList = $orderModel->getOrderInfoByOId($orderid, $uid);
        } elseif($orderType == self::PARENT_ORDER_ID) {
            $orderList = $orderModel->getOrderInfoByPOId($orderid, $uid);
        }
        
        if(empty($orderList)) {
            $this->_exit(40013);
        }
        $arr = [];
        $totalPrice = 0;
        $subject = '';
        $body = '';
        foreach($orderList as $info) {
            if(!in_array($info['order_id'], $arr)) {
                $arr[] = $info['order_id'];
                $totalPrice += $info['total_price'];
            }
            $subject .= $info['goods_name'] . ',';
            $body .= $info['goods_name'] . ',';
        }
        $subject    = rtrim($subject, ',');
        $body       = rtrim($body, ',');
        
        //支付宝支付
        if($payType == self::ALIPAYMENT) {
            $alipay = new Alipay();
            $alipay->alipay_config = Yii::$app->params['alipay'];
            
            //支付类型。默认值为：1（商品购买）
            $payment_type = 1; 
            $notify_url = Yii::$app->params['mall_domain'].'/mall/order/alipaynotify';
            $return_url = '';
            //商户订单号
            $out_trade_no = $orderid;
            //订单名称,传入商品名
            //$subject = 'sofa';
            //付款金额
            $total_fee = $totalPrice/100.0;
            
            //订单描述
            //$body = '';
            //超时时间
            $it_b_pay = '';
            //钱包token
            $extern_token = '';
            
            $parameter = [
                'service'       => 'mobile.securitypay.pay',
                'partner'       => trim($alipay->alipay_config['partner']),
                'seller_id'     => trim($alipay->alipay_config['seller_id']),
                'payment_type'	=> $payment_type,
                'notify_url'	=> $notify_url,
                'return_url'	=> $return_url,
                'out_trade_no'	=> $out_trade_no,
                'subject'		=> $subject,
                'total_fee'		=> $total_fee,
                'body'	        => $body,
                'it_b_pay'		=> $it_b_pay,
                'extern_token'	=> $extern_token,
                '_input_charset'=> trim(strtolower($alipay->alipay_config['input_charset']))
            ];
            $paramData = $alipay->buildRequestParaToString($parameter);
            if($paramData) {
                $this->_exit(0, ['payInfo' => $paramData]);
            } else {
                $this->_exit(-1);
            }
        } elseif($payType == self::WXPAYMENT) {
            //微信支付
            $wxpay = new Wxpay();
            $wxpay->wxpay_config = Yii::$app->params['wxpay'];
            
            //随机字符串
            $nonce_str = $this->rand_str(32);
            //附加数据，在查询API和支付通知中原样返回
            $attach = $orderType;
            //商户订单号
            $out_trade_no = $orderid;
            //货币类型
            $fee_type = 'CNY';
            //总金额
            $total_fee = $totalPrice;
            //终端IP
            $spbill_create_ip = $_SERVER['REMOTE_ADDR'];
            //通知地址
            $notify_url = Yii::$app->params['mall_domain'].'/mall/order/wxpaynotify';
            //交易类型
            $trade_type = 'APP';
            $parameter = [
                'appid' => trim($wxpay->wxpay_config['appid']),
                'mch_id' => trim($wxpay->wxpay_config['mch_id']),
                'nonce_str' => $nonce_str,
                'body' => mb_substr($subject, 0, 20, 'utf-8'),
                'attach' => $attach,
                'out_trade_no' => $out_trade_no,
                'fee_type' => $fee_type,
                'total_fee' => $total_fee,
                'spbill_create_ip' => $spbill_create_ip,
                'notify_url' => $notify_url,
                'trade_type' => $trade_type,
            ];
            $sign = $wxpay->makeSign($parameter);
            $parameter['sign'] = $sign;
            $xml = $wxpay->toXml($parameter);
            $res = $wxpay->postXmlCurl($xml, Wxpay::UNIFIEDORDER_URL);
            if(!$res) {
                $this->_exit(-1);
            }
            //得到返回的数组
            $retParams = $wxpay->fromXml($res);
            if($retParams['return_code'] == 'SUCCESS' && $retParams['result_code'] == 'SUCCESS') {
                $return = [
                    'appid'         => $parameter['appid'],
                    'partnerid'     => $parameter['mch_id'],
                    'prepayid'      => $retParams['prepay_id'],
                    'package'       => 'Sign=WXPay',
                    'noncestr'      => $retParams['nonce_str'],
                    'timestamp'     => time()
                ];
                $sign = $wxpay->makeSign($return);
                $ret = [
                    'appid' => $return['appid'],
                    'partnerid' => $return['partnerid'],
                    'prepayid' => $return['prepayid'],
                    'packageInfo' => $return['package'],
                    'noncestr' => $return['noncestr'],
                    'timestamp' => $return['timestamp'],
                    'sign' => $sign
                ];
                $this->_exit(0, $ret);
            } else {
                $this->_exit(-1);
            }
        }
    }
    /**
     * 获取客服号码 城市列表 支付方法
     * */
    public function actionService()
    {
        $info=[];
        $info['paytype']=Yii::$app->params['pay_type'];
        $info['tel']=Yii::$app->params['service_phone'];
        //$info['tel']="123456";
        $model = new City();
        $arr = [];
        $countries = $model->getAreaByPid(0);
        foreach($countries as $key=>$country) {
            $arr[$key]['id']      = $country['id'];
            $arr[$key]['country'] = $country['name_cn'];
        
            $provinces = $model->getAreaByPid($country['id']);
            if($provinces) {
                foreach($provinces as $k=>$province) {
                    $arr[$key]['level2'][$k]['id'] = $province['id'];
                    $arr[$key]['level2'][$k]['province'] = $province['name_cn'];
        
                    $cities = $model->getAreaByPid($province['id']);
                    foreach($cities as $subK=>$city) {
                        $arr[$key]['level2'][$k]['level3'][$subK]['id']     = $city['id'];
                        $arr[$key]['level2'][$k]['level3'][$subK]['city']   = $city['name_cn'];
                        $towns = $model->getAreaByPid($city['id']);
                        foreach($towns as $sk=>$town) {
                            $arr[$key]['level2'][$k]['level3'][$subK]['level4'][$sk]['id']   = $town['id'];
                            $arr[$key]['level2'][$k]['level3'][$subK]['level4'][$sk]['town'] = $town['name_cn'];
                        }
                    }
                }
            }
        }
        $info['citylist']=$arr;
        $this->_exit(0,$info);
    }
}
